<template>
  <div class="app-container">
    <el-row style="width: 100%;height: 100%;margin: 0;" :gutter="10">
      <!--区域数据-->
      <el-col :span="4" style="height: 100%;padding-left: 0;">
        <div style="background-color: #FFFFFF;height: 100%;padding: 10px;">
          <el-input placeholder="输入关键字进行过滤" clearable size="mini" suffix-icon="el-icon-search"
                    style="width: 100%;" v-model="filterText"/>
          <div style="height: 96%; max-height:96%;overflow-y: auto;margin-top: 10px;" class="treeCont">
<!--            :default-expanded-keys="[2, 3]"-->
            <el-tree
              :default-expanded-keys="defaultExpandedKeys"
              :data="sheetsTreeList"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              node-key="sheetsCode"
              :highlight-current="true"
              v-loading="treeLoading"
              :current-node-key="currentKey"
              @node-click="handleNodeClick"
            >
              <template #default="{ node, data}">
                <div class="custom-tree-node"
                      style="display: flex;justify-content: center;align-items: center;font-size: 14px;">
                  <span class="iconfont icon-a-jiafangzijianzhu icon-padding" v-if="data.deviceType === 0"></span>
                  <span class="iconfont icon-loudong icon-padding" v-if="data.deviceType === 1"></span>
                  <span class="iconfont icon-a-homezhuyefangzijia icon-padding" v-if="data.deviceType === 2"></span>
                  <span>{{ node.label }}</span>
                  <span v-if="data.deviceCount!=null" class="device-count">({{data.deviceCount}})</span>
                </div>
              </template>
            </el-tree>
          </div>
        </div>
      </el-col>

      <el-col :span="20" style="height: 100%;background-color: #FFFFFF;">
        <div style="width: 100%;margin: 10px 5px 10px 0;">
          <el-row class="line-bottom" v-show="showSearch">
            <el-col class="form_col">
              <el-form :model="queryParams" ref="queryForm" :size="formItemSize" v-show="showSearch"
                       :label-width="labelWidth">
                <div id="searchFilter" style="display: flex; flex-wrap: wrap">
                  <el-form-item label="用户名称" prop="userName">
                    <el-input :size="formItemSize"
                              v-model="queryParams.userName"
                              placeholder="请输入用户名称"
                              clearable
                              @keyup.enter.native="handleQuery"/>
                  </el-form-item>
                  <el-form-item label="用户编号" prop="userId">
                    <el-input :size="formItemSize"
                              v-model="queryParams.userId"
                              placeholder="请输入用户编号"
                              clearable
                              @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="设备编号" prop="terminalId">
                    <el-input :size="formItemSize"
                              v-model="queryParams.terminalId"
                              placeholder="请输入设备编号"
                              clearable
                              @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="IMEI" prop="imei">
                    <el-input :size="formItemSize"
                              v-model="queryParams.imei"
                              placeholder="输入imei"
                              clearable
                    />
                  </el-form-item>
                  <el-form-item label="注册平台" prop="signPlatform">
                    <el-select filterable v-model="queryParams.signPlatform" placeholder="请选择注册平台" style="width: 100%;">
                      <el-option v-for="dict in dict.type.sign_platform" :key="dict.value" :label="dict.label"
                                 :value="parseInt(dict.value)"></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-form>
            </el-col>
            <el-col class="form_query" style="line-height: 1;padding: 0;">
              <el-button v-show="collapseAble" size="mini" type="text" @click="shiftCollapseAble" class="text">
              <span>
                {{ fold ? '收起筛选' : '更多筛选' }}
              </span>
              </el-button>
              <el-button type="primary" @click="handleQuery" size="mini">查询</el-button>
              <el-button @click="resetQuery" size="mini">重置</el-button>
              <RightDropdown :columns="columns" :showSearch.sync="showSearch" :queryVisible=false @queryTable="getList" @export="handleExport"
                             :hasPermiExport="['datastatistics:realtimegatherdataxb:export']" style="margin-left: 10px;"></RightDropdown>
            </el-col>
          </el-row>
          <el-table ref="table" v-loading="loading" :data="dataList" border size="mini"
                    :default-sort="defaultSort" @sort-change="handleSorterChange" :height="getAvailableHeight">
            <el-table-column type="index" label="#" width="40" align="center"/>
            <el-table-column label="设备编号" align="center" prop="terminalId" v-if="columns[2].visible"
                             sortable="custom" :sort-orders="['ascending','descending']" :show-overflow-tooltip="true"
                             width="140">
              <template slot-scope="scope">
                <router-link :to="{name: 'HistoryXb', params: {locationNb: scope.row.locationNb,terminalId: scope.row.terminalId}}" style="color: #00afff">{{scope.row.terminalId}}</router-link>
              </template>
            </el-table-column>
            <el-table-column label="抄表时间" align="center" prop="readDate" v-if="columns[8].visible"
                             sortable="custom" :sort-orders="['ascending','descending']" :show-overflow-tooltip="true"
                             width="170">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.readDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="用户名称" align="center" prop="userName" v-if="columns[0].visible"
                             sortable="custom" :sort-orders="['ascending','descending']" :show-overflow-tooltip="true"/>
            <el-table-column label="用户编号" align="center" prop="userId" v-if="columns[1].visible"
                             sortable="custom" :sort-orders="['ascending','descending']" :show-overflow-tooltip="true"/>
<!--            <el-table-column label="门牌号" align="center" prop="installAddress" v-if="columns[2].visible"-->
<!--                             sortable="custom" :sort-orders="['ascending','descending']" :show-overflow-tooltip="true"/>-->
            <el-table-column label="IMEI" align="center" prop="imei" v-if="columns[3].visible"
                             sortable="custom" :show-overflow-tooltip="true"
                             width="150"/>
            <el-table-column label="水表读数(m³)" align="center" prop="totalFlow" v-if="columns[4].visible"
                             sortable="custom" :sort-orders="['ascending','descending']" :show-overflow-tooltip="true"
                             width="150"/>
            <el-table-column label="终端电压(V)" align="center" prop="terminalVol" v-if="columns[5].visible"
                             sortable="custom" :sort-orders="['ascending','descending']" :show-overflow-tooltip="true"
                             width="150"/>
            <el-table-column label="阀门状态" align="center" prop="valveState" v-if="columns[6].visible"
                             sortable="custom" :sort-orders="['ascending','descending']" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span v-if="scope.row.valveState === 1">开</span>
                <span v-if="scope.row.valveState === 0">关</span>
              </template>
            </el-table-column>
            <el-table-column label="信号强度" align="center" prop="terminalCsq" v-if="columns[7].visible"
                             sortable="custom" :sort-orders="['ascending','descending']" :show-overflow-tooltip="true"/>

          </el-table>
          <pagination :total="total"
                      :page.sync="queryParams.pageNum"
                      :limit.sync="queryParams.pageSize"
                      @pagination="getList"
          />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getAreaTree } from "@/api/tree/index"
import {listRealtimegatherdataXbView, getRealtimegatherListXbView} from "@/api/dataquery/metered/realtimegatherdataXbView";

export default {
  name: "Realtimegatherdataxb",
  dicts: ['belong_department', 'sign_platform'],
  data() {
    return {
      defaultExpandedKeys: [],
      // 区域树的宽度
      treeWidth: "",
      currentKey: "",
      screenHeight: null,
      formItemSize: 'mini',
      collapseAble: false,
      fold: false,
      maxShow: 4,
      labelWidth: '70px',
      // 列信息
      columns: [
        {key: 0, label: `用户名称`, visible: true},
        {key: 1, label: `用户编号`, visible: true},
        {key: 2, label: `设备编号`, visible: true},
        {key: 3, label: `IMEI`, visible: true},
        {key: 4, label: `水表读数`, visible: true},
        {key: 5, label: `终端电压`, visible: true},
        {key: 6, label: `阀门状态`, visible: true},
        {key: 7, label: `信号强度`, visible: true},
        {key: 8, label: `抄表时间`, visible: true},
      ],
      defaultProps: {
        children: "children",
        label: "sheetsName"
      },
      filterText: '',
      // 默认排序
      defaultSort: {prop: 'readDate', order: 'descending'},
      // 区域树选项
      sheetsTreeList: [],
      // 遮罩层
      loading: false,
      treeLoading: false,
      TerminalIDs: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 实时数据采集（小）表格数据
      dataList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        sheetsCode: null,
        userName: null,
        userId: null,
        terminalId: null,
        loginUserId: null,
        systemFlag: null,
        signPlatform: null,
        imei: null,
      },
    };
  },
  created() {
    this.screenHeight = document.body.clientHeight
  },
  computed: {
    getAvailableHeight() {
      return this.screenHeight - (this.showSearch ? (this.fold ? 250 : 211) : 165)
    },
    userId() {
      return this.$store.state.user.userId
    },
    systemFlag() {
      return this.$store.state.user.systemFlag
    }
  },
  mounted() {
    this.getTreeList();
    this.treeWidth = this.$refs['tree']?.$el.offsetWidth - 15
    // 通过最大显示个数控制展开/折叠
    if (this.maxShow > 0) {
      this.minShowControl()
    }
  },
  watch: {
    // 根据名称筛选区域树
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    /** 排序触发事件 */
    handleSorterChange({column, prop, order}) {
      this.queryParams.orderByColumn = prop
      this.queryParams.isAsc = order
      this.getList()
    },
    /** 检查设置排序字段 */
    checkSortColumn() {
      if (!this.queryParams.orderByColumn) {
        this.queryParams.orderByColumn = this.defaultSort.prop
        this.queryParams.isAsc = this.defaultSort.order
      }
    },
    // // 初始化表格 解决表格固定操作列的问题
    // init() {
    //   // 调用接口获取到数据后
    //   let _self = this
    //   this.$nextTick(() => {
    //     window.setTimeout(() => {
    //       _self.$refs.table.doLayout()
    //     }, 100)
    //   })
    // },
    // 展开折叠按钮
    shiftCollapseAble() {
      this.fold = !this.fold
      this.minShowControl()
    },
    // 通过maxShow控制元素显示/折叠
    minShowControl() {
      const group = window.document.querySelectorAll(`#searchFilter .el-form-item.el-form-item--${this.formItemSize}`)
      const len = group?.length ? group?.length : 0
      if (this.maxShow < len) {
        group.forEach((item, index) => {
          if (index > this.maxShow - 1 && index < len) {
            item.hidden = !this.fold
          }
        })
        this.collapseAble = true
      } else {
        this.collapseAble = false
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.sheetsName.indexOf(value) !== -1;
    },
    /** 查询区域树 */
    getTreeList() {
      this.treeLoading = true;
      // let treeType = "0,1"
      // getAreaTree(treeType).then(response => {
      //   this.sheetsTreeList = response.data;
      //   this.defaultExpandedKeys = [this.sheetsTreeList[0].sheetsCode];
      //   this.currentKey = this.sheetsTreeList[0].sheetsCode
      //   this.$nextTick(() => {
      //     window.setTimeout(() => {
      //       this.$refs.tree.setCurrentKey(this.currentKey)
      //       this.$refs.tree.setCurrentNode(this.sheetsTreeList[0])
      //     }, 100)
      //   })
      //   this.getList();
      //   this.treeLoading = false;
      // });
      this.sheetsTreeList = JSON.parse(localStorage.getItem('meteredTreeData'))
      this.defaultExpandedKeys = [this.sheetsTreeList[0].sheetsCode];
      if(this.sheetsTreeList.length === 0) {
        this.treeLoading = false;
      }else {
        // if(this.systemFlag !== 0) {
        //   this.currentKey = this.sheetsTreeList[0].sheetsCode
        //   this.$nextTick(() => {
        //     window.setTimeout(() => {
        //       this.$refs.tree.setCurrentKey(this.currentKey)
        //       this.$refs.tree.setCurrentNode(this.sheetsTreeList[0])
        //     }, 100)
        //   })
          this.getList();
        // }else{
        //   this.currentKey = ''
        //   this.$nextTick(() => {
        //     window.setTimeout(() => {
        //       this.$refs.tree.setCurrentKey(this.currentKey)
        //       this.$refs.tree.setCurrentNode(this.sheetsTreeList[0])
        //     }, 100)
        //   })
        //   this.getList();
        // }
        this.treeLoading = false;
      }
    },
    /** 查询实时数据采集（小）列表 */
    getList() {
      this.checkSortColumn()
      this.loading = true;
      let choiceCheck = this.$refs.tree.getCurrentNode()
      this.queryParams.systemFlag = this.systemFlag
      this.queryParams.loginUserId = this.userId
      if (!choiceCheck) {
        // this.$modal.msgWarning("请选择一个区域查看数据!")
        this.queryParams.sheetsCode = ''
      } else {
        this.queryParams.sheetsCode = choiceCheck.sheetsCode
      }
      getRealtimegatherListXbView(this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        // this.init()
        this.loading = false;
      });
    },
    handleNodeClick(data) {
      this.handleQuery()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.$refs.tree.setCurrentKey(null)
      this.handleQuery();
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('datastatistics/realtimegatherdataxb/export', {
        ...this.queryParams
      }, `户表实时数据.xlsx`)
    }
  }
};
</script>
<style scoped lang="scss">
// 设置本身箭头为隐藏状态
::v-deep .el-tree-node__expand-icon {
  width: 20px;
  padding: 0;
  margin: 5px 0;

  svg {
    display: none;
    width: 0;
  }
}

// 虚线所需样式
::v-deep .treeCont {
  .el-tree-node{
    width: fit-content;
    min-width: var(--treeWidth);
  }
  .el-tree > .el-tree-node:before {
    //border-top: none;
    padding-left: 0px;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
  }

  .el-tree-node__content {
    padding-left: 5px !important;
  }

  .el-tree-node__children {
    //overflow: visible !important;
    .el-tree-node {
      position: relative;
      padding-left: 5px;
    }
  }

  //节点有间隙，隐藏掉展开按钮就好了,如果觉得空隙没事可以删掉
  .el-tree-node__expand-icon.is-leaf {
    width: 4px;
  }

  .el-tree-node__children {
    padding-left: 18px;
  }

  .el-tree-node :last-child:before {
    height: 17px;
  }

  .el-tree > .el-tree-node:before {
    border-left: none;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
    top: 25px;
    width: 0px;
  }

  .el-tree-node:before {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:after {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:before {
    border-left: 1px dashed #c0c4cc;
    height: 100%;
    top: -3px;
    width: 1px;
  }

  .el-tree-node:after {
    border-top: 1px dashed #c0c4cc;
    height: 0px;
    top: 13px;
    width: 16px;
  }
}

// 默认三角行换成加减号
::v-deep .treeCont {
  .el-tree-node__content > .el-tree-node__expand-icon {
    width: 16px;
    //width: 0px;
    padding: 0px;
    font-size: 16px !important;
    margin-right: 5px; //新增
  }

  .el-tree .el-tree-node__expand-icon.expanded {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }

  //有子节点 且未展开
  .el-tree .el-tree-node__expand-icon:before {
    background: url('../../../../assets/images/jia.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  .custom-tree-node .el-icon svg {
    display: block !important;
    color: #000;
  }

  //有子节点 且已展开
  .el-tree .el-tree-node__expand-icon.expanded:before {
    background: url('../../../../assets/images/jian.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  //没有子节点
  .el-tree .el-tree-node__expand-icon.is-leaf::before {
    background: none;
    content: "";
    display: block;
    width: 20px;
    height: 20px ;
    font-size: 20px;
    background-size: 100% 100%;
  }
}
//.form_col {
//  width: 80%;
//
//  ::v-deep .el-form {
//    width: 100%;
//  }
//
//  ::v-deep .el-form-item {
//    width: 23%;
//  }
//}
//
//.form_query {
//  width: 20%;
//  text-align: right;
//}
</style>
